<?php

require_once (GAME_CONFIG_FILE);
require_once (USER_CONTROLLER_FILE);
require_once (CARDS_DECK_FILE);
require_once (RANDOM_FILE);
require_once (DB_FILE);

// Game Init Function (used by waiting_state.php to create new game row in games table)
class GameInit {
    
    /** STATIC PART **/
    private static $ErrorMSG = "";
    
    private static $GameID;
    
    
    
    public static function getErrorMSG() {
        return self::$ErrorMSG;
    }
    public static function getGameID() {
        return self::$GameID;
    }
    
    private static function getEmptyBoard()  {
        // fill the board var with empty board (INIT BOARD)
        $board_count = ROW_SIZE * COL_SIZE * CARD_SOLDIER_LEN;
        $new_board = "";
        for ($i=0 ; $i<$board_count ; $i++) {
            $new_board .= "x";
        }
        return $new_board;
    }
    
    private static function getInitTower()  {
        // fill the tower var with new towers (INIT TOWER)
        $tower_count = ROW_SIZE;
        $new_tower = "";
        for ($i=0 ; $i<$tower_count ; $i++) {
            $new_tower .= TOWER_HP;
        }
        return $new_tower;
    }
    
    private static function getInitDeck()  {
        //get few randomly cards for starting
        
        // fill empty card tmp
        $empty_card = "";
        for ( $j=0 ; $j<CARD_SEG_LEN ; $j++ ) {
            $empty_card .= "x";
        }       
        
        // fill deck with random cards
        $deck = "";
        for ($i=0 ; $i<INIT_CARDS_COUNT ; $i++) {
            $card = CardsDeck::Instance()->random_card_id();
            // padd with zerros according to CARD_SEG_LEN
            for($j=  strlen($card) ; $j<CARD_SEG_LEN ; $j++) {
                $card = "0" . $card;
            }
            $deck .= $card;
        }
        // fill the rest with empty cards
        for (;$i<MAX_CARD_HOLDING ; $i++) {
            $deck .= $empty_card;
        }
        
        return $deck;
    }
    

    // 1. check if waiting table is not empty
    // False on ERROR
    // OK: OK_START_GAME\WAIT_TO_START_GAME 
    public static function StartWaiting() {
        // check for other users that wait
        // take the oldest player that waits
        $db = new DBConnection();
        $query = "SELECT *
                    FROM waiting
                    WHERE DATE(time) = (
                       SELECT MIN(DATE(time))
                       FROM waiting )";                    
        if ($db->executeQuery($query)) {
            $result = $db->getResult();
            // check if some user already waiting
            if( ($result != null) && ($result->num_rows > 0) ) {
                // FOUND OP. , 
                // now generate new game for you(op) 
                // and the waiting player (in "uid")
                // and let him know about it!        
                $row = $result->fetch_assoc();
                // Create New EMPTY Game Row
                $my_uid = UserController::getUserID();
                
                // Sanity check
                if ( $row["uid"] == $my_uid) {
                    // the waiting player is ME - WTF?!
                    if ( $row['op_uid'] != null ) {
                        // and op_UID is not empty..strange..
                        self::$ErrorMSG = 'op_uid exist';
                        return false;
                    }
                    else {
                        //ok' just hack, but nevermind...continue to wait
                        //$_SESSION["waiting_game_id"] = $row['id'] ;
                        $_SESSION["waiting_started"] = 1;
                        return WAIT_TO_START_GAME;
                    }
                }
                
                // Try to insert new game row
                $new_game_id = self::InsertNewGameRow($row["uid"], $my_uid);
                if ( $new_game_id ) {
                    // Insert new game row - OK!
                    // now update the waiting row with the new game_id and the op. uid
                    
                    $query = "UPDATE waiting
                        SET op_uid=$my_uid, game_id=" . $new_game_id . "
                         WHERE id=" . $row["id"] . ";";
                    if ($db->executeQuery($query)) {
                        $result = $db->getResult();
                        if( ($result != null)  ) {
                            //  OK, we can start playing!
                            //  Just update in user table the game_id ($new_game_id)!!
                            $query = "UPDATE users
                                SET game_id=" . $new_game_id . "
                                 WHERE id=" . $my_uid. ";";   
                            if ($db->executeQuery($query)) {
                                $result = $db->getResult();
                                if( ($result != null)  ) {
                                    // OK , done with prep..Lets Play!
                                    // set session PLAYING to true
                                    // set session waiting_started to false (done waiting)
                                    UserController::SetPlaying(1);
                                    UserController::SetGameID($new_game_id);
                                    $_SESSION["waiting_started"] = 0;
                                    return OK_START_GAME;    // Lets PLAY
                                    //header( 'Location: game.php' ) ;    // Lets PLAY                                    
                                }
                                else {
                                    // error with update
                                    self::$ErrorMSG = $db->getErrorMSG();
                                    return false;                                    
                                }
                            }
                            else {
                                // DB Error
                                self::$ErrorMSG = $db->getErrorMSG();
                                return false;                                
                            }
                        }      
                        else {
                            // error with update
                            self::$ErrorMSG = $db->getErrorMSG();
                            return false;
                        }
                    }
                    else {
                        // error with update
                        self::$ErrorMSG = $db->getErrorMSG();
                        return false;                        
                    }
                }
                else {
                    // ERROR InsertNewGameRow, msg already exist
                    return false;    
                }
            }
            else { 
                // NO user is waiting (table is EMPTY) 
                // create new waiting row
                $db = new DBConnection();
                
                $my_uid = UserController::getUserID();
                
                $query = "INSERT INTO waiting (
                    uid) VALUES (
                    $my_uid);";    
                
                if ($db->executeQuery($query)) {
                    $result = $db->getResult();   
                    if ( $result != null ) {
                        // OK inserted new row
                        // just wait from now on...
                        $_SESSION["waiting_started"] = 1;
                        return WAIT_TO_START_GAME;
                    }
                }
                else {
                    // error with DB
                    self::$ErrorMSG = $db->getErrorMSG();
                    return false;
                }
            }
        }
        else {
            // DB ERROR!
            self::$ErrorMSG = 'DBError:' . $db->getErrorMSG(); 
            return true;            
        }
    }
    
    // inserting new game row (assuming validation first)
    private static function InsertNewGameRow($p1_id , $p2_id)  {
        
        // Setup Turns
        $p_array = array($p1_id, $p2_id);   //player array - Arr[p1,p2] of uid
        $turn_bool = Random::get_random_num(0, 1); // rnd (0/1)
        $turn = $p_array[$turn_bool];   // put uid in turn of the first player to play
        $turn_array = array(0,0);       // init turn array
        $turn_array[$turn_bool] = 1;    // put 1 in the player that play 1st
        
        // Setup game
        $new_board = self::getEmptyBoard();
        $new_tower = self::getInitTower();
        $p1_cards  = self::getInitDeck();
        $p2_cards  = self::getInitDeck();
        
        $time = time();

        $query = 'INSERT INTO games(
            p1_id, p2_id,
            p1_board, p2_board,
            p1_towers, p2_towers,
            p1_cards, p2_cards,
            turn, p1_turn, p2_turn,
            start_time, last_time,
            last_action)
            VALUES ( '. $p1_id . ',' . $p2_id . ',
            "' . $new_board . '", "' . $new_board . '",
            "' . $new_tower . '", "' . $new_tower . '",
            "' . $p1_cards . '", "' . $p2_cards . '",
            ' . $turn . ', ' . $turn_array[0] . ', ' . $turn_array[1] . ', 
            ' . $time . ', ' . $time . ', 
            "");';        
        
        $db = new DBConnection();
        if ($db->executeQuery($query)) {
            $result = $db->getResult();
            if( $result != null ) {
                // OK! new game added to table
                return $db->getLastInsertID();  //return game ID
            }
            else {
                self::$ErrorMSG = $db->getErrorMSG();
                return false;
            }
        }  
        else {
            self::$ErrorMSG = $db->getErrorMSG();
            return false;
        }
    }    
    
    
    //1. if you are still waiting, check for update
    public static function CheckForUpdate() {
        
        //$id = $_SESSION["waiting_game_id"];
        
        $db = new DBConnection();
        
        $query = "SELECT *
                    FROM waiting
                    WHERE uid = ?";            
        
        $my_uid = UserController::getUserID();
        if ($db->executeBindedQuery($query,"i", $my_uid)) {
            $result = $db->getResult();

            if( ($result != null) && ($result->num_rows > 0) ) {
                //row found
                //now check for updates (if op. joind the game)
                $row = $result->fetch_assoc();
                if ( $row["op_uid"] != null ) {
                    // FOUND OP.!
                    // 1. delete this row (no waiting anymore!)
                    // 2. update the user table with the game id
                    // and 3. Join the game
                    
                    //1. del waiting row
                    $query = "DELETE FROM waiting
                        WHERE id=" . $row["id"] . ";";
                    if ($db->executeQuery($query) ) {
                        // ok, row deleted
                        // 2.now update GameID in user table

                        $new_game_id = $row["game_id"];
                        
                        $query = "UPDATE users
                            SET game_id=" . $new_game_id . "
                             WHERE id=" . $my_uid. ";";   
                        
                        if ($db->executeQuery($query)) {
                            $result = $db->getResult();
                            if( ($result != null)  ) {
                                // 3. OK , done with prep..Lets Play!
                                // set session PLAYING to true
                                // set session waiting_started to false (done waiting)
                                UserController::SetPlaying(1);
                                UserController::SetGameID($new_game_id);
                                $_SESSION["waiting_started"] = 0;
                                return OK_START_GAME;    // Lets PLAY
                                //header( 'Location: game.php' ) ;    // Lets PLAY                                    
                            }
                            else {
                                // error with update
                                self::$ErrorMSG = $db->getErrorMSG();
                                return false;                                    
                            }
                        }
                        else {
                            // error with update
                            self::$ErrorMSG = $db->getErrorMSG();
                            return false;                              
                        }
                    }
                    else {
                        // DB Error (while del waiting row)
                        self::$ErrorMSG = $db->getErrorMSG();
                        return false;                            
                    }
                }
                else {
                    // No Update
                    // No op. found
                    // Still Wait
                    return WAIT_TO_START_GAME;
                }
            }
            else {
                //user not waiting, some hack maybe...
                echo 'go away hackers';
                die();
            }
        }
        else {  //DB Error
            self::$ErrorMSG = $db->getErrorMSG();
            return false;            
        }
    }
    
    
    // User req to cancel his waiting status
    public static function CancelWaiting() {
        // remove row from Waiting Table (if exist..)
        $db = new DBConnection();
        $my_uid = UserController::getUserID();
        $query = "DELETE FROM waiting 
                    WHERE uid = $my_uid;";    
        $db->executeQuery($query);
        //unset status        
        UserController::SetWatingForGame(0);
        unset( $_SESSION["waiting_started"] );
    }
    
    
}